﻿using System;
using Hvam.SharePoint.Search.Query.Site.Models;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Taxonomy;
using System.Linq;

namespace Hvam.SharePoint.Search.Query.Site.ResultSteps
{
    internal class TaxIdFieldExtractorResultStep : SiteSearchResultStep
    {
        public TaxIdFieldExtractorResultStep(SiteSearchQuery query)
            : base(query)
        {
        }

        public override SiteSearchResult Process(SiteSearchResult result)
        {
            var item = result.ListItem;

            foreach (var property in Query.RequestedProperties.Where(s => s.StartsWith("owstaxId", StringComparison.OrdinalIgnoreCase)))
            {
                var fieldName = property.Substring(8);

                if (!Query.RequestedFields.ContainsKey(fieldName))
                {
                    continue;
                }

                var field = Query.RequestedFields[fieldName];
                var key = property;
                if (result.Properties.ContainsKey(key))
                {
                    continue;
                }

                string value;

                switch (field.TypeAsString)
                {
                    case "TaxonomyFieldType":
                        var t = GetValue(item, field);
                        if (t is TaxonomyFieldValue)
                        {
                            var taxonomyFieldValue = (TaxonomyFieldValue) t;
                            value = taxonomyFieldValue.TermGuid;
                        }
                        else
                        {
                            value = "SiteSearch: Unsupported taxonomy owstaxid field value.";
                        }
                        break;
                    default:
                        value = "SiteSearch: Unsupported owstaxid field type.";
                    break;
                }

                result.Properties.Add(key, value);
            }

            return result;
        }

        private object GetValue(SPListItem item, SPField field)
        {
            try
            {
                return item[field.Id];
            }
            catch (ArgumentException)
            {
                return null;
            }
        }
    }
}
